Popular Searches
Popular Course Categories
Popular Courses

Windows and Tabs

Handling Browser Components

Windows and Tabs in Selenium WebDriver

Windows and Tabs are important browser automation concepts in Selenium WebDriver. Modern web applications frequently open pages in new browser tabs or windows when users click links, buttons, reports, help pages, external services, authentication links, documentation, or other resources.

Selenium WebDriver represents browser tabs and windows using unique Window Handles. To automate elements inside another tab or window, Selenium must first switch its control from the current browser context to the required window handle.

For complete Selenium WebDriver training, Java automation, TestNG, framework development, real-time projects, and advanced browser interactions, visit JustAcademy Selenium Training and Register for Selenium Course Demo.


1. What Are Windows and Tabs?

A browser window is a browser context that can contain one or more tabs. A browser tab is another page opened within the browser. From Selenium WebDriver's point of view, both tabs and windows are handled through window handles.

Every browser context controlled by WebDriver has a unique identifier called a Window Handle.

Browser Session

|

|-- Main Tab / Window

|      Handle A

|

|-- New Tab

|      Handle B

|

|-- New Window

       Handle C


2. Why Is Window and Tab Handling Required?

When a new tab or window opens, Selenium does not automatically move its focus to the newly opened browser context. The WebDriver session remains focused on the current context until the test explicitly switches to another handle.

For example:

Main Window

     |

     | Click "Open Report"

     v

New Tab Opens

     |

     | Selenium is still on Main Window

     v

Get Window Handles

     |

     v

Find New Tab Handle

     |

     v

Switch to New Tab

     |

     v

Perform Test Actions


3. What Is a Window Handle?

A window handle is a unique string identifier used by Selenium WebDriver to identify a particular browser window or tab during a WebDriver session.

The handle of the currently selected browser context can be obtained using:

String currentWindow = driver.getWindowHandle();

Window handles are generated dynamically for the browser session, so they should not normally be hard-coded.


4. getWindowHandle()

The getWindowHandle() method returns the handle of the currently active browser window or tab.

String parentWindow = driver.getWindowHandle();

 

System.out.println("Current Window: " + parentWindow);

This handle is commonly stored before opening a new tab so that the test can return to the original page later.


5. getWindowHandles()

The getWindowHandles() method returns the handles of all currently available browser windows and tabs in the WebDriver session.

Set<String> allWindows = driver.getWindowHandles();

 

System.out.println("Number of Windows: " + allWindows.size());

The return type is Set<String> because each window handle is unique.


6. getWindowHandle() vs getWindowHandles()

MethodPurposeReturn Type
getWindowHandle()Returns the currently active browser contextString
getWindowHandles()Returns all available browser contextsSet<String>


7. switchTo().window()

The switchTo().window() method is used to switch Selenium's focus from one browser window or tab to another.

driver.switchTo().window(windowHandle);

After switching, Selenium commands such as findElement(), getTitle(), getCurrentUrl(), and element interactions operate on the selected browser context.


8. Parent Window and Child Window

The browser context that is active before opening another tab or window is commonly called the parent window. The newly opened browser context is commonly called the child window.

Parent Window

      |

      | Click link

      v

Child Window

      |

      | Perform validation

      v

Switch back

      |

      v

Parent Window

These are useful test-automation terms. Selenium fundamentally identifies the contexts using window handles.


9. Basic Parent-Child Window Handling

String parentWindow = driver.getWindowHandle();

 

driver.findElement(By.id("openWindow")).click();

 

Set<String> allWindows = driver.getWindowHandles();

 

for (String window : allWindows) {

 

    if (!window.equals(parentWindow)) {

 

        driver.switchTo().window(window);

 

        break;

    }

}


10. Complete Basic Example

import java.util.Set;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class WindowHandlingExample {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        driver.get("https://example.com");

 

        String parentWindow = driver.getWindowHandle();

 

        driver.findElement(By.id("openWindow")).click();

 

        Set<String> windows = driver.getWindowHandles();

 

        for (String window : windows) {

 

            if (!window.equals(parentWindow)) {

 

                driver.switchTo().window(window);

 

                System.out.println(

                    "Child Title: " + driver.getTitle());

 

                break;

            }

        }

 

        driver.switchTo().window(parentWindow);

 

        driver.quit();

    }

}


11. Switching Back to the Parent Window

After finishing the work in the child tab or window, switch back using the previously stored parent handle.

driver.switchTo().window(parentWindow);

This is one of the most important steps in multi-window automation because Selenium will continue working in whichever browser context is currently selected.


12. Handling Multiple Windows

An application may open multiple tabs or windows during a test.

Set<String> allWindows = driver.getWindowHandles();

 

for (String window : allWindows) {

 

    driver.switchTo().window(window);

 

    System.out.println("Handle: " + window);

    System.out.println("Title: " + driver.getTitle());

    System.out.println("URL: " + driver.getCurrentUrl());

}

This approach allows the test to inspect every browser context.


13. Identifying a Window by Title

When several windows are available, the required window can be identified using its page title.

for (String window : driver.getWindowHandles()) {

 

    driver.switchTo().window(window);

 

    if (driver.getTitle().contains("Reports")) {

 

        System.out.println("Reports window found");

 

        break;

    }

}


14. Identifying a Window by URL

The current URL can also be used to identify a particular window.

for (String window : driver.getWindowHandles()) {

 

    driver.switchTo().window(window);

 

    if (driver.getCurrentUrl().contains("reports")) {

 

        System.out.println("Reports page found");

 

        break;

    }

}


15. Identifying a Window Using a Unique Page Element

In some applications, the title or URL may not be unique. In such cases, the test can switch through the available windows and check for a page-specific element.

for (String window : driver.getWindowHandles()) {

 

    driver.switchTo().window(window);

 

    if (!driver.findElements(

            By.id("reportTable")).isEmpty()) {

 

        System.out.println("Report window found");

 

        break;

    }

}


16. Using Iterator for Window Handles

An Iterator can be used to access window handles individually.

Set<String> windows = driver.getWindowHandles();

 

Iterator<String> iterator = windows.iterator();

 

String parentWindow = iterator.next();

String childWindow = iterator.next();

 

driver.switchTo().window(childWindow);

This approach is simple for basic scenarios, but for complex applications it is better to identify windows by meaningful properties such as title or URL rather than assuming a particular order.


17. Using Java Stream

Java Streams can also be used to locate a window other than the parent window.

String parentWindow = driver.getWindowHandle();

 

String childWindow = driver.getWindowHandles()

        .stream()

        .filter(handle -> !handle.equals(parentWindow))

        .findFirst()

        .orElseThrow();

 

driver.switchTo().window(childWindow);


18. Opening a New Tab in Selenium 4

Selenium 4 provides the newWindow() method to create a new browser tab or window.

To create a new tab:

driver.switchTo().newWindow(WindowType.TAB);

The WebDriver focus moves to the newly created tab.


19. Opening a New Window in Selenium 4

To create a new browser window:

driver.switchTo().newWindow(WindowType.WINDOW);

This creates a new window and switches the WebDriver focus to it.


20. New Tab Example

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WindowType;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class NewTabExample {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        driver.get("https://example.com");

 

        String parentWindow = driver.getWindowHandle();

 

        driver.switchTo().newWindow(WindowType.TAB);

 

        driver.get("https://www.selenium.dev");

 

        System.out.println(

            "New Tab Title: " + driver.getTitle());

 

        driver.switchTo().window(parentWindow);

 

        System.out.println(

            "Parent Title: " + driver.getTitle());

 

        driver.quit();

    }

}


21. New Window Example

driver.get("https://example.com");

 

String parentWindow = driver.getWindowHandle();

 

driver.switchTo().newWindow(WindowType.WINDOW);

 

driver.get("https://www.selenium.dev");

 

System.out.println(driver.getTitle());

 

driver.switchTo().window(parentWindow);


22. Tab vs Window

FeatureBrowser TabBrowser Window
Selenium IdentificationWindow HandleWindow Handle
Switching APIswitchTo().window()switchTo().window()
Selenium 4 CreationWindowType.TABWindowType.WINDOW
Can contain web elementsYesYes
Requires switching when not activeYesYes


23. Windows and Tabs vs Frames

Windows/TabsFrames/iFrames
Separate browser contextsEmbedded browsing contexts inside a page
Use window handlesUse frame switching
switchTo().window()switchTo().frame()
Return using a window handleUse parentFrame() or defaultContent()


24. Windows and Tabs vs Alerts

Windows/TabsAlerts
Have window handlesHandled through Alert API
Use switchTo().window()Use switchTo().alert()
Contain web pagesBrowser dialog
Can contain normal web elementsHandled using alert methods


25. Waiting for a New Tab or Window

A new browser context may not appear immediately after clicking a link or button. If Selenium tries to retrieve the handles too quickly, the newly opened context may not yet be available.

Use an explicit wait:

WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

wait.until(d -> d.getWindowHandles().size() > 1);


26. Complete Example with Explicit Wait

import java.time.Duration;

import java.util.Set;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.WebDriverWait;

 

public class WindowWaitExample {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        driver.get("https://example.com");

 

        String parentWindow = driver.getWindowHandle();

 

        driver.findElement(By.id("openWindow")).click();

 

        WebDriverWait wait =

            new WebDriverWait(driver, Duration.ofSeconds(10));

 

        wait.until(d ->

            d.getWindowHandles().size() > 1);

 

        Set<String> windows = driver.getWindowHandles();

 

        for (String window : windows) {

 

            if (!window.equals(parentWindow)) {

 

                driver.switchTo().window(window);

 

                System.out.println(

                    driver.getTitle());

 

                break;

            }

        }

 

        driver.switchTo().window(parentWindow);

 

        driver.quit();

    }

}


27. Why Thread.sleep() Is Not Recommended

A common beginner approach is to use:

Thread.sleep(5000);

This introduces a fixed delay. If the new tab opens quickly, the test unnecessarily waits. If the application takes longer than the fixed duration, the test may still fail.

Instead, wait for a meaningful condition:

WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

wait.until(d ->

    d.getWindowHandles().size() > 1);


28. Waiting for a Specific Number of Windows

WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

wait.until(d ->

    d.getWindowHandles().size() == 2);

This waits until exactly two browser contexts are available.


29. Finding the Newly Opened Window

A robust technique is to capture the existing handles before the action and compare them with the handles after the new window appears.

Set<String> oldWindows =

    driver.getWindowHandles();

 

driver.findElement(By.id("openWindow")).click();

 

WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

wait.until(d ->

    d.getWindowHandles().size() > oldWindows.size());

 

Set<String> newWindows =

    driver.getWindowHandles();

 

newWindows.removeAll(oldWindows);

 

String newWindow =

    newWindows.iterator().next();

 

driver.switchTo().window(newWindow);


30. Handling Multiple Child Windows

Suppose the application opens several additional browser contexts.

Main Window

    |

    |-- Child Window 1

    |

    |-- Child Window 2

    |

    |-- Child Window 3

All handles can be inspected:

for (String handle : driver.getWindowHandles()) {

 

    driver.switchTo().window(handle);

 

    System.out.println(

        "Title: " + driver.getTitle());

 

    System.out.println(

        "URL: " + driver.getCurrentUrl());

}


31. Handling Multiple Windows by Title

String parentWindow =

    driver.getWindowHandle();

 

for (String handle :

        driver.getWindowHandles()) {

 

    driver.switchTo().window(handle);

 

    if (driver.getTitle()

            .contains("Payment")) {

 

        System.out.println(

            "Payment Window Found");

 

        break;

    }

}

 

driver.switchTo().window(parentWindow);


32. Handling Multiple Windows by URL

String parentWindow =

    driver.getWindowHandle();

 

for (String handle :

        driver.getWindowHandles()) {

 

    driver.switchTo().window(handle);

 

    if (driver.getCurrentUrl()

            .contains("checkout")) {

 

        System.out.println(

            "Checkout Window Found");

 

        break;

    }

}

 

driver.switchTo().window(parentWindow);


33. Handling a Window by Page Element

String parentWindow =

    driver.getWindowHandle();

 

for (String handle :

        driver.getWindowHandles()) {

 

    driver.switchTo().window(handle);

 

    if (!driver.findElements(

            By.id("checkoutForm")).isEmpty()) {

 

        System.out.println(

            "Checkout Page Found");

 

        break;

    }

}

 

driver.switchTo().window(parentWindow);


34. Closing a Child Tab or Window

The close() method closes the currently selected browser tab or window.

driver.close();

After closing a browser context, explicitly switch to another valid context.

driver.close();

 

driver.switchTo().window(parentWindow);


35. close() vs quit()

MethodPurpose
close()Closes the currently selected browser window or tab
quit()Closes all browser windows and ends the WebDriver session

close()

driver.close();

quit()

driver.quit();


36. Important Rule After close()

Consider this sequence:

driver.switchTo().window(childWindow);

 

driver.close();

 

driver.switchTo().window(parentWindow);

This ensures that Selenium continues with a valid browser context instead of attempting further actions on a closed window.


37. Opening a Link in a New Tab

A web page may contain a link with target="_blank":

<a href="https://example.com" target="_blank">

    Open Example

</a>

When the browser opens the link in another tab or window, Selenium can discover the additional context through window handles.


38. Practical Example: Support Page

String parentWindow =

    driver.getWindowHandle();

 

driver.findElement(

    By.id("supportLink")).click();

 

WebDriverWait wait =

    new WebDriverWait(

        driver,

        Duration.ofSeconds(10));

 

wait.until(d ->

    d.getWindowHandles().size() > 1);

 

for (String handle :

        driver.getWindowHandles()) {

 

    if (!handle.equals(parentWindow)) {

 

        driver.switchTo().window(handle);

 

        System.out.println(

            "Support Page: " +

            driver.getTitle());

 

        break;

    }

}

 

driver.switchTo().window(parentWindow);


39. Practical Example: Terms and Conditions

String parentWindow =

    driver.getWindowHandle();

 

driver.findElement(

    By.linkText("Terms and Conditions"))

    .click();

 

new WebDriverWait(

    driver,

    Duration.ofSeconds(10))

    .until(d ->

        d.getWindowHandles().size() > 1);

 

for (String handle :

        driver.getWindowHandles()) {

 

    driver.switchTo().window(handle);

 

    if (driver.getTitle()

            .contains("Terms")) {

 

        System.out.println(

            "Terms Page Opened");

 

        break;

    }

}

 

driver.close();

 

driver.switchTo().window(parentWindow);


40. Practical Example: Reports

String mainWindow =

    driver.getWindowHandle();

 

driver.findElement(

    By.id("generateReport")).click();

 

new WebDriverWait(

    driver,

    Duration.ofSeconds(10))

    .until(d ->

        d.getWindowHandles().size() > 1);

 

for (String handle :

        driver.getWindowHandles()) {

 

    driver.switchTo().window(handle);

 

    if (driver.getCurrentUrl()

            .contains("report")) {

 

        System.out.println(

            "Report Window Found");

 

        break;

    }

}

 

driver.switchTo().window(mainWindow);


41. Practical Example: External Authentication

Some test environments may use an external authentication page in another tab or window. The automation should switch to the required test context, perform authorized test actions, and then return to the main application.

String mainWindow =

    driver.getWindowHandle();

 

driver.findElement(

    By.id("externalLogin")).click();

 

new WebDriverWait(

    driver,

    Duration.ofSeconds(10))

    .until(d ->

        d.getWindowHandles().size() > 1);

 

for (String handle :

        driver.getWindowHandles()) {

 

    driver.switchTo().window(handle);

 

    if (driver.getCurrentUrl()

            .contains("test-auth")) {

 

        System.out.println(

            "Authentication Window Found");

 

        break;

    }

}

 

driver.switchTo().window(mainWindow);


42. Dynamic Window Handles

Window handles should not normally be hard-coded because they are generated dynamically for the WebDriver session.

Prefer:

String parent =

    driver.getWindowHandle();

 

Set<String> handles =

    driver.getWindowHandles();

Then identify the required handle using reliable application information.


43. Checking Number of Open Tabs/Windows

int windowCount =

    driver.getWindowHandles().size();

 

System.out.println(

    "Open Windows/Tabs: " +

    windowCount);

This is useful for synchronization, validation, and debugging.


44. Verifying That a New Window Opened

int initialCount =

    driver.getWindowHandles().size();

 

driver.findElement(

    By.id("openWindow")).click();

 

new WebDriverWait(

    driver,

    Duration.ofSeconds(10))

    .until(d ->

        d.getWindowHandles().size()

        > initialCount);

 

System.out.println(

    "New Window Opened");


45. Printing All Window Information

for (String handle :

        driver.getWindowHandles()) {

 

    driver.switchTo().window(handle);

 

    System.out.println(

        "Handle: " + handle);

 

    System.out.println(

        "Title: " + driver.getTitle());

 

    System.out.println(

        "URL: " + driver.getCurrentUrl());

 

    System.out.println(

        "----------------------");

}


46. Reusable Window Utility

In a large Selenium automation framework, repeated window-switching code can be placed inside a utility class.

import java.time.Duration;

 

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.support.ui.WebDriverWait;

 

public class WindowUtils {

 

    public static void waitForNewWindow(

            WebDriver driver,

            int expectedCount) {

 

        WebDriverWait wait =

            new WebDriverWait(

                driver,

                Duration.ofSeconds(10));

 

        wait.until(d ->

            d.getWindowHandles().size()

            >= expectedCount);

    }

 

    public static void switchToWindowByTitle(

            WebDriver driver,

            String expectedTitle) {

 

        for (String handle :

                driver.getWindowHandles()) {

 

            driver.switchTo().window(handle);

 

            if (driver.getTitle()

                    .contains(expectedTitle)) {

 

                return;

            }

        }

 

        throw new RuntimeException(

            "Window not found: "

            + expectedTitle);

    }

 

    public static void switchToWindowByUrl(

            WebDriver driver,

            String expectedUrl) {

 

        for (String handle :

                driver.getWindowHandles()) {

 

            driver.switchTo().window(handle);

 

            if (driver.getCurrentUrl()

                    .contains(expectedUrl)) {

 

                return;

            }

        }

 

        throw new RuntimeException(

            "Window not found: "

            + expectedUrl);

    }

}


47. Using Window Utility

String parentWindow =

    driver.getWindowHandle();

 

driver.findElement(

    By.id("openReport")).click();

 

WindowUtils.waitForNewWindow(

    driver, 2);

 

WindowUtils.switchToWindowByTitle(

    driver, "Report");

 

System.out.println(

    driver.getTitle());

 

driver.switchTo().window(

    parentWindow);


48. Window Handling with Page Object Model

In the Page Object Model, application-specific actions can be kept inside page classes while reusable window operations can be placed in utility classes.

public class HomePage {

 

    private WebDriver driver;

 

    public HomePage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void openHelpPage() {

 

        driver.findElement(

            By.id("help")).click();

    }

 

    public String getCurrentWindow() {

 

        return driver.getWindowHandle();

    }

}


49. TestNG Example

import java.time.Duration;

 

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.WebDriverWait;

import org.testng.Assert;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.Test;

 

public class WindowTest {

 

    WebDriver driver;

 

    @BeforeMethod

    public void setup() {

 

        driver = new ChromeDriver();

 

        driver.manage()

              .window()

              .maximize();

    }

 

    @Test

    public void verifyNewWindow() {

 

        driver.get("https://example.com");

 

        String parentWindow =

            driver.getWindowHandle();

 

        // Action that opens a new tab/window

 

        new WebDriverWait(

            driver,

            Duration.ofSeconds(10))

            .until(d ->

                d.getWindowHandles().size() > 1);

 

        for (String handle :

                driver.getWindowHandles()) {

 

            if (!handle.equals(parentWindow)) {

 

                driver.switchTo()

                      .window(handle);

 

                Assert.assertFalse(

                    driver.getTitle().isEmpty());

 

                break;

            }

        }

    }

 

    @AfterMethod

    public void tearDown() {

 

        if (driver != null) {

            driver.quit();

        }

    }

}


50. Common Exceptions

ExceptionPossible Cause
NoSuchWindowExceptionTrying to use a window that has been closed or is unavailable
TimeoutExceptionExpected window did not appear within the wait period
NoSuchElementExceptionElement is not present in the currently selected page
StaleElementReferenceExceptionPreviously located element is no longer valid after a context/page change


51. NoSuchWindowException

NoSuchWindowException can occur when Selenium attempts to interact with a browser context that no longer exists.

driver.switchTo().window(childWindow);

 

driver.close();

 

// The child window is already closed

// Further interaction with it can fail

After closing the child, switch to a remaining valid context.


52. TimeoutException

A timeout can occur if a new tab or window does not become available within the configured wait period.

WebDriverWait wait =

    new WebDriverWait(

        driver,

        Duration.ofSeconds(10));

 

wait.until(d ->

    d.getWindowHandles().size() > 1);


53. Common Mistake: Not Switching to the New Tab

A common error is clicking a link that opens another tab and then immediately searching for an element from that tab without switching.

Incorrect:

driver.findElement(

    By.id("openTab")).click();

 

driver.findElement(

    By.id("childElement")).click();

Correct:

String parent =

    driver.getWindowHandle();

 

driver.findElement(

    By.id("openTab")).click();

 

new WebDriverWait(

    driver,

    Duration.ofSeconds(10))

    .until(d ->

        d.getWindowHandles().size() > 1);

 

for (String handle :

        driver.getWindowHandles()) {

 

    if (!handle.equals(parent)) {

 

        driver.switchTo()

              .window(handle);

 

        break;

    }

}

 

driver.findElement(

    By.id("childElement")).click();


54. Common Mistake: Forgetting the Parent Handle

Always store the original handle before opening another tab or window.

String parentWindow =

    driver.getWindowHandle();

Without storing it, returning to the original page becomes less straightforward when several windows are present.


55. Common Mistake: Hard-Coding Window Handles

Do not depend on a fixed string as a window handle.

Incorrect:

driver.switchTo()

      .window("hard-coded-window");

Correct:

Set<String> handles =

    driver.getWindowHandles();

 

for (String handle : handles) {

 

    driver.switchTo().window(handle);

 

    // Identify required window

}


56. Common Mistake: Assuming Window Order

For simple examples, an Iterator can be convenient, but robust automation should not depend on an assumed order of handles.

Instead of blindly assuming that the second handle is the required window, identify it using:

  • Page title
  • Current URL
  • Unique page element
  • Expected window count
  • Other application-specific conditions


57. Common Mistake: Not Waiting for the New Context

If the application opens the new tab asynchronously, Selenium may collect the handles before the new context is available.

Use:

new WebDriverWait(

    driver,

    Duration.ofSeconds(10))

    .until(d ->

        d.getWindowHandles().size() > 1);


58. Common Mistake: Closing the Wrong Window

Before calling close(), verify which browser context is currently active.

System.out.println(

    "Current Title: " +

    driver.getTitle());

 

System.out.println(

    "Current URL: " +

    driver.getCurrentUrl());

This is especially useful when several tabs are open.


59. Window Handling Workflow

Start Test

    |

    v

Open Application

    |

    v

Store Parent Handle

    |

    v

Click Link / Button

    |

    v

New Tab / Window Opens

    |

    v

Wait for New Handle

    |

    v

Get All Handles

    |

    v

Identify Required Handle

    |

    v

Switch to Required Window

    |

    v

Perform Test Actions

    |

    v

Validate Page

    |

    v

Close Child if Required

    |

    v

Switch to Parent

    |

    v

Continue Test

    |

    v

Quit Browser


60. Best Practices

  • Always store the parent window handle before opening a new browser context.
  • Use getWindowHandles() to discover available tabs and windows.
  • Use switchTo().window() to switch between browser contexts.
  • Use explicit waits when a new tab/window is opened asynchronously.
  • Identify windows using title, URL, or another reliable application-specific condition.
  • Avoid hard-coded window handles.
  • Avoid unnecessary Thread.sleep().
  • After closing a child window, switch to a valid remaining window.
  • Use Selenium 4's newWindow() when the test itself needs to create a tab or window.
  • Use reusable utilities for large automation frameworks.
  • Use quit() to clean up the complete WebDriver session.


61. Real-World Applications

Application AreaExample
ReportsReport opens in a new tab
DocumentationDocumentation opens in another tab
SupportSupport portal opens separately
AuthenticationAuthentication page opens in another browser context
External ServicesExternal test service opens separately
Terms and ConditionsLegal information opens in a new tab
Product ComparisonComparison page opens separately
PreviewPreview page opens in another tab


62. Mini Project: Multi-Tab Website Validation

Create a Selenium automation project in which the main application contains links for Documentation, Support, and Company Information. Each link opens a new browser tab.

Requirements

  1. Open the main application.
  2. Store the parent window handle.
  3. Click the Documentation link.
  4. Wait for the new tab.
  5. Switch to the Documentation tab.
  6. Validate the title or URL.
  7. Close the Documentation tab.
  8. Return to the parent.
  9. Repeat for Support.
  10. Repeat for Company Information.
  11. Quit the browser after all validations.

Project Flow

Main Application

      |

      +-- Documentation

      |       |

      |       +-- New Tab

      |       +-- Validate

      |       +-- Close

      |

      +-- Support

      |       |

      |       +-- New Tab

      |       +-- Validate

      |       +-- Close

      |

      +-- Company

              |

              +-- New Tab

              +-- Validate

              +-- Close

                      |

                      v

                 Main Application


63. Complete Multi-Tab Example

import java.time.Duration;

import java.util.Set;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.WebDriverWait;

 

public class MultiTabTest {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        driver.manage()

              .window()

              .maximize();

 

        driver.get("https://example.com");

 

        String parentWindow =

            driver.getWindowHandle();

 

        driver.findElement(

            By.id("documentation")).click();

 

        WebDriverWait wait =

            new WebDriverWait(

                driver,

                Duration.ofSeconds(10));

 

        wait.until(d ->

            d.getWindowHandles().size() > 1);

 

        Set<String> handles =

            driver.getWindowHandles();

 

        for (String handle : handles) {

 

            if (!handle.equals(parentWindow)) {

 

                driver.switchTo()

                      .window(handle);

 

                System.out.println(

                    "Child Title: " +

                    driver.getTitle());

 

                System.out.println(

                    "Child URL: " +

                    driver.getCurrentUrl());

 

                driver.close();

 

                break;

            }

        }

 

        driver.switchTo()

              .window(parentWindow);

 

        System.out.println(

            "Parent Title: " +

            driver.getTitle());

 

        driver.quit();

    }

}


64. Windows and Tabs in Page Object Model

A scalable automation framework can separate page-specific actions, window utilities, and test validation.

Test Class

    |

    +-- Page Objects

    |

    +-- Window Utility

    |

    +-- Wait Utility

    |

    +-- Test Data

    |

    +-- Assertions

    |

    v

Browser Automation


65. Interview Questions

Q1. What is a window handle in Selenium?

A window handle is a unique identifier used by Selenium WebDriver to identify a browser window or tab.

Q2. Which method returns the current window handle?

driver.getWindowHandle();

Q3. Which method returns all window handles?

driver.getWindowHandles();

Q4. How do you switch to another tab?

driver.switchTo().window(handle);

Q5. How do you return to the parent window?

driver.switchTo().window(parentWindow);

Q6. What is the difference between close() and quit()?

close() closes the currently selected browser context, while quit() closes all browser contexts and ends the WebDriver session.

Q7. How do you handle multiple tabs?

Retrieve all window handles, iterate through them, identify the required browser context using title, URL, or another reliable condition, and switch using switchTo().window().

Q8. Can Selenium handle both browser tabs and windows?

Yes. Selenium WebDriver handles both through window handles.

Q9. How do you wait for a new tab?

new WebDriverWait(

    driver,

    Duration.ofSeconds(10))

    .until(d ->

        d.getWindowHandles().size() > 1);

Q10. How do you create a new tab in Selenium 4?

driver.switchTo()

      .newWindow(WindowType.TAB);


66. Advanced Interview Questions

Q1. How would you identify a particular window when five windows are open?

Store the required parent handle, retrieve all handles, switch through the available contexts, and identify the required one using a reliable property such as its title, URL, or unique page element.

Q2. Why should window handles not be hard-coded?

Window handles are dynamically generated for the current WebDriver session and should therefore be retrieved at runtime.

Q3. What happens after closing the current window?

The closed browser context can no longer be used. The test should switch to another valid remaining window before continuing.

Q4. How can you verify that a new window opened?

Capture the number or set of handles before the action, perform the action, and wait until the number of available handles increases.

Q5. How do you handle an unknown number of tabs?

Use getWindowHandles() dynamically and iterate through all available contexts while identifying the required page using application-specific information.


67. Quick Cheat Sheet

TaskSelenium Code
Get current windowdriver.getWindowHandle()
Get all windowsdriver.getWindowHandles()
Switch windowdriver.switchTo().window(handle)
Create new tabdriver.switchTo().newWindow(WindowType.TAB)
Create new windowdriver.switchTo().newWindow(WindowType.WINDOW)
Close current tab/windowdriver.close()
Close entire browser sessiondriver.quit()
Get current titledriver.getTitle()
Get current URLdriver.getCurrentUrl()
Wait for additional contextwait.until(d -> d.getWindowHandles().size() > 1)


68. Windows and Tabs Checklist

  • Store the parent handle.
  • Perform the action that opens the new tab/window.
  • Wait for the new browser context.
  • Get all window handles.
  • Identify the required handle.
  • Switch using switchTo().window().
  • Perform validation and actions.
  • Close the child when appropriate.
  • Switch back to the parent.
  • Continue the test.
  • Use quit() after the complete test.


69. Learning Exercise

Create a Selenium test that performs the following workflow:

  1. Open the main website.
  2. Save the parent window handle.
  3. Open a new tab using Selenium 4.
  4. Navigate to another test page.
  5. Print the new tab title.
  6. Print the new tab URL.
  7. Switch back to the parent.
  8. Create another window.
  9. Navigate to a different test page.
  10. Identify the new window using its title.
  11. Validate an element.
  12. Close the child window.
  13. Return to the parent.
  14. Quit the WebDriver session.


70. Important Concepts to Remember

  • getWindowHandle() returns the current browser context handle.
  • getWindowHandles() returns all available browser context handles.
  • switchTo().window() switches Selenium to another browser context.
  • close() closes the current tab or window.
  • quit() closes all browser contexts and terminates the WebDriver session.
  • WindowType.TAB can be used with Selenium 4 to create a new tab.
  • WindowType.WINDOW can be used with Selenium 4 to create a new window.
  • Window handles are dynamically generated.
  • Explicit waits are useful when new browser contexts appear asynchronously.
  • Windows/tabs, frames, and alerts use different Selenium switching mechanisms.


71. Final Interview Answer

Question: How do you handle multiple windows or tabs in Selenium?

Answer: Selenium handles browser windows and tabs using unique window handles. First, I store the current window handle using getWindowHandle(). Then I perform the action that opens the new tab or window and wait until the additional browser context becomes available. I retrieve all handles using getWindowHandles(), identify the required window using its title, URL, or another reliable condition, and switch to it using driver.switchTo().window(handle). After completing the required actions, I can close the child window if required and switch back to the parent window using its stored handle. In Selenium 4, I can also create a new tab or window using newWindow(WindowType.TAB) or newWindow(WindowType.WINDOW).


72. Summary

Windows and Tabs handling is an essential part of Selenium WebDriver automation. Whenever a web application opens another browser tab or window, Selenium must identify and switch to the corresponding window handle before interacting with elements in that context.

The basic workflow is to save the parent handle, perform the action that opens a new context, wait for the new handle, retrieve all handles, identify the required window, switch using switchTo().window(), perform the required validation or interaction, and finally return to the parent window.

For reliable automation, avoid hard-coded handles and unnecessary fixed delays. Use explicit waits, title/URL validation, reusable window utilities, Page Object Model practices, and proper browser-session cleanup.


73. Selenium Course Resources

Learn Windows and Tabs together with Selenium WebDriver, Java, TestNG, locators, waits, frames, alerts, advanced browser interactions, automation frameworks, and real-world testing projects:


74. Final Quick Revision

Current Browser Context

        |

        v

driver.getWindowHandle()

        |

        v

Store Parent Handle

        |

        v

Open New Tab / Window

        |

        v

Wait for New Context

        |

        v

driver.getWindowHandles()

        |

        v

Identify Required Handle

        |

        v

driver.switchTo().window(handle)

        |

        v

Perform Actions

        |

        v

driver.close() if required

        |

        v

driver.switchTo().window(parentHandle)

        |

        v

Continue Test

        |

        v

driver.quit()

whatsapp